package com.watson.juc.pc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DemoLock {
    public static void main(String[] args) throws InterruptedException {
        // 多线程操作
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 600; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 600; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 600; i++) {
                ticket.sale();
            }
        }, "C").start();
    }

//    public static void main(String[] args) throws InterruptedException {
//        // 多线程操作
//        Ticket01 ticket = new Ticket01();
//        new Thread(() ->{
//            for (int i = 0; i < 60; i++) {
//                ticket.sale();
//            }
//        },"B").start();
//        new Thread(() ->{
//            for (int i = 0; i < 60; i++) {
//                ticket.sale();
//            }
//        },"A").start();
//        new Thread(() ->{ for (int i = 0; i < 60; i++) ticket.sale(); },"C").start();
//    }
}


class Ticket {
    private int number = 6000;

    public synchronized void sale() {
        if (number > 0) {
            System.out.println(Thread.currentThread() + "卖出第" + (number - number--) + "剩余" + number);
        }
    }
}

class Ticket01 {
    private int number = 500;
    Lock lock = new ReentrantLock();

    public void sale() {
        //加锁
        lock.lock();

        try {
            //业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread() + "卖出第" + (50 - number--) + "剩余" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
